
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  query.fieldlist;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;

import logger.PoolLogger;

import dbmanager.DBManager;
import dbmanager.GetIdName;

/**
 * @author   wiki
 */
public class Master_table implements Fieldlist
{
	GetIdName gid;
	String CONDITION="Condition";
	String FIELDLIST="field";
	String MASTERNAME="mastername";
	String buffer[];
	String fieldString = null;
	String Fieldobject="";
	/**
	 * @uml.property  name="object"
	 */
	String object;
	String reportName;
	String ALIES="alies";
	Vector<Object> FieldVector;
	String QUERY;
	String Split[]={};
	String Querybuffer[];
	PoolLogger pl;
	
	public Master_table() {
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	/**
	 * set database object and find master id of Field
	 * @param db is database object
	 */
	public void initFieldList() 
	{
		gid = new GetIdName();	
		MASTERNAME = gid.getId(MASTERNAME);
	}
	/**
	 *  return buffer
	 * @return buffer : String array
	 */ 
	@SuppressWarnings("unchecked")
	public String [] getbuffer()
	{
		StringBuffer FinalResult = new StringBuffer();
		try 
		{
			for(int i=0;i<FieldVector.size();i++)
			{	
				try {
					Hashtable<Object, Object> tempfieldlist = new Hashtable<Object, Object>();
					tempfieldlist = (Hashtable<Object, Object>) FieldVector.get(i);
					if(tempfieldlist.containsKey(ALIES))
					{
						String name =gid.getItem(tempfieldlist.get(ALIES).toString());
						if(name.equals("no$"))
							name =(tempfieldlist.get(ALIES).toString());
						FinalResult.append(name +"\t");				
					}		
					else
					{	
						String name =gid.getItem(tempfieldlist.get(FIELDLIST).toString());
						if(name.equals("no$"))
							name =(tempfieldlist.get(FIELDLIST).toString());
						FinalResult.append(name+"\t");
					}
				} catch (Exception e) 
				{
					e.printStackTrace();
				}	
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		Hashtable<Object, Object> resulthash =new Hashtable<Object, Object>();
		try 
		{
			ResultSet rs = DBManager.getSelect(QUERY);
			while(rs.next())
			{	
				String mastername=rs.getString("mid");
				if(resulthash.containsKey(mastername))
				{
					Vector<Object> propertyvector= (Vector<Object>) resulthash.get(mastername);
					Hashtable<Object, Object> propertyhash =new Hashtable<Object, Object>();					
					String key =  (rs.getString("pid"));
					String value =  (rs.getString("pv"));
					if(value.equals("0"))
						value = rs.getString("vt");
					else	
						value = gid.getItem(value);
					try {
						propertyhash.put(key, value);
					} catch (Exception e) {
						propertyhash.put(key, "null");
					}
					propertyvector.add(propertyhash);
				}
				else					
				{
					Vector<Object> propertyvector= new Vector<Object>();
					Hashtable<Object, Object> propertyhash =new Hashtable<Object, Object>();					
					String key =  (rs.getString("pid"));
					String value =  (rs.getString("pv"));
					if(value.equals("0"))
						value = rs.getString("vt");
					else	
						value = gid.getItem(value);
					propertyhash.put(key, value);
					propertyvector.add(propertyhash);
					resulthash.put(mastername,propertyvector);
				}	
			}
		}
		catch (SQLException e2) 
		{	
			e2.printStackTrace();
		}
		
		FinalResult.append("\n");
		Enumeration<Object> enumforresulthash = resulthash.keys();
		while(enumforresulthash.hasMoreElements())
		{
			String mastername = enumforresulthash.nextElement().toString();

			Vector<Object> property = new Vector<Object>();
			property.addAll( (Collection<? extends Object>) resulthash.get(mastername));
			
			for(int i=1;i<Split.length;i++)
			{
				try {
					boolean flag=false;
					if(Split[i].equals(MASTERNAME))
						FinalResult.append(gid.getItem(mastername)+"\t");
					else
					{
						for(int j=0;j<property.size();j++)					
						{
							Hashtable<Object, Object> temphash= new Hashtable<Object, Object>();
							temphash.putAll((Map<? extends Object, ? extends Object>) property.get(j));
							if(temphash.containsKey(Split[i]))
							{
								FinalResult.append(temphash.get(Split[i]).toString()+"\t");
								flag = true;
								break;
							}
						}	
						if(!flag)
							FinalResult.append("null\t");
					}
				} catch (RuntimeException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
			}
			FinalResult.append("\n");
		}
			
		String temp = FinalResult.toString();
		buffer = temp.split("\n");

		return buffer;
	}
	/**
	 * set buffer
	 * @param buffer:String Array 
	 */
	public void setbuffer(String buffer[])
	{
		this.buffer = buffer;
	}
	/**
	 * set field Object 
	 * @param Object  is condition object
	 * @uml.property  name="fieldVector"
	 */
	public void setFieldVector(Vector<Object> FieldVector)
	{
		this.FieldVector = FieldVector;
	}
	/**
	 * generate final buffer by finding all field  
	 * @return void
	 */
	@SuppressWarnings("unchecked")
	public void getResult()
	{
		int Querylength=QUERY.length();
		int count=1;
		Split = new String[FieldVector.size()+1];
		if(FieldVector.size()>0)
			QUERY = QUERY + " and (";
		boolean flag=false;
		for(int i=0;i<FieldVector.size();i++)
		{			
			Hashtable<Object, Object> tempfieldlist = new Hashtable<Object, Object>();
			tempfieldlist = (Hashtable<Object, Object>) FieldVector.get(i);
			if(tempfieldlist.containsKey(FIELDLIST))
			{
				Split[count] = tempfieldlist.get(FIELDLIST).toString();
				if(!Split[count].equals(MASTERNAME))
					QUERY = QUERY + " p_2.pid=" + Split[count] + " or ";
				else	
					flag = true;
				count++;
			}		
		}
		if(flag==true && FieldVector.size()==1)
		{
			QUERY = QUERY.substring(0, QUERY.length()-6);
		}
		if(Querylength<QUERY.length())
		{
			QUERY =  QUERY.substring(0,QUERY.length()-3);
			QUERY = QUERY + ")";
		}	
		if(QUERY.indexOf("WHERE")!=-1)
			QUERY = QUERY + " AND p_2.td is null"; 
	}
	
	public static void main(String[] args) 
	{
		/*
		Master_table mt =new Master_table();
		combinereport.condition.Master_table con = new combinereport.condition.Master_table();
		con.setDbmanager(db);
		//con.setObject("6260");
		//con.initializeData();
		
		
		Hashtable<Object, Object> table =new Hashtable<Object, Object>();
		Vector<Object> condition = new Vector<Object>();
		table.put(combinereport.condition.Condition.CONDITIONFIELD, "9");
		table.put(combinereport.condition.Condition.CONDITIONVALUE, "25");
		table.put("logicaloperator", "and");
		condition.add(table);		
		Hashtable<Object, Object> table1 =new Hashtable<Object, Object>();
		table1.put(combinereport.condition.Condition.CONDITIONFIELD, "7");
		table1.put(combinereport.condition.Condition.CONDITIONVALUE, "549");
		table1.put("logicaloperator", "and");
		condition.add(table1);
		con.setConditionMap(condition);		
		con.getResult(); 
		con.QUERY
	//	mt.setbuffer(con.getbuffer());
		//mt.setObject("6246");
		mt.setDbmanager(db);
		mt.getResult();
		String buffer2[] = mt.getbuffer();
		for(int i=0;i<buffer2.length;i++)
		{
			System.out.println(buffer2[i]);
		}
		//find retailer,emailid where mobileno +919922918607
		 //mt.getResult("|field,mastername,mobileno,Personcode,emailid|Condition,=,type,Employee,");
		//mt.getResult("|field,type|Condition,personcode,=,aac");
		//mt.getResult("|field,|Condition,type,=,user");
		//mt.getResult("|field,mastername|Condition,type,=,user");//for i card
		//mt.getResult("|field,");*/
	}

	/**
	 * @return
	 * @uml.property  name="object"
	 */
	public String getObject() 
	{
		return Fieldobject;
	}
	/**
	 * generate final buffer   <p> when process is add in report_master then addreport method is called.
	 * addreport method call getresult method <p>
	 */

	public void addReport()
	{
		getResult();
	}

	/**
	 * @param reportName
	 * @uml.property  name="reportName"
	 */
	public void setReportName(String reportName) 
	{
		this.reportName = reportName;
	}
	/**
	 * generate final buffer   <p> when process is mod in report_master then updatereport method is called.
	 * updatereport method call getresult method <p>
	 */
	public void updateReport() 
	{
		getResult();
	}
	public String getQuery() 
	{
		return QUERY;
	}
	public void setQuery(String Query) 
	{
		this.QUERY = Query;	
	}
	
	public void setQueryCount(int count) {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * @param Querybuffer
	 * @uml.property  name="querybuffer"
	 */
	public void setQuerybuffer(String[] Querybuffer) 
	{
		this.Querybuffer = Querybuffer;
	}	
}

